/**
 * Created by Weizehua on 2017/1/27.
 */

import {logger} from "../src/Core/Logger/Logger";
// logger.setLevel('DEBUG');
logger.setLevel('DEBUG');

import {loadAllTests} from "./TestLoader";
import {Main} from "../src/Process";
import {Injector} from "ts.di";
import {Database} from "../src/Core/Database/Database";
import {ConnectionOptions, Connection} from "typeorm";
import {DailyHeat, WeeklyHeat, MonthlyHeat} from "../src/Album/AlbumsHeat";
import {Spot} from "../src/Image/Spot";
import {Image} from "../src/Image/Image";
import {Album} from "../src/Album/Album";
import {User} from "../src/User/User";
import {Permission} from "../src/User/Permission";
import {SMSSentInfo} from "../src/SMS/SMSSentInfo";

let typeormOptions: ConnectionOptions = {
    driver: {
        type: "mysql",
        host: "192.168.10.131",
        username: "petestuser",
        password: "Wzh0403!",
        database: "pe-test"
    },
    entities: Database.tables,
    autoSchemaSync: true,
    logging: {
        logQueries: true
    }
};

async function exec(main:Main) {
    await main.loadFactories();
    await main.connectToDatabase(typeormOptions);
    await main.loadHandlers();
    await main.runHttpServer();
    await clearDatabase();
    loadAllTests();
}
async function clearDatabase() {

    let typeorm = Injector.get(Connection);

    // pe entities
    await typeorm.entityManager.clear(DailyHeat);
    await typeorm.entityManager.clear(WeeklyHeat);
    await typeorm.entityManager.clear(MonthlyHeat);
    await typeorm.entityManager.clear(Spot);
    await typeorm.entityManager.clear(Image);
    await typeorm.entityManager.clear(Album);
    await typeorm.entityManager.clear(Permission);
    await typeorm.entityManager.clear(User);

    // third party
    await typeorm.entityManager.clear(SMSSentInfo);
}

function errorHandler(e:Error){
    logger.error(`!!!Error raised to root: ${e.name} : ${e.message}
stack trace: ${e.stack}`);
}

process.on("unhandledRejection", (reason, p) => {
    logger.error(p);
});

let main = new Main();
exec(main).catch(errorHandler);
